import React, { useEffect, useMemo, useState } from 'react';
import { StyleSheet, TouchableOpacity } from 'react-native';
import Tools from '../../../utils/Tools.ts';
import { Text, View } from 'native-base';
import { FasterImageView } from '@candlefinance/faster-image';
import AntDesign from 'react-native-vector-icons/AntDesign';
import { CommonStyle } from '../../../common/commonStyle.ts';
import Ionicons from 'react-native-vector-icons/Ionicons';
import { useDispatch, useSelector } from 'react-redux';
import { AppDispatch, RootState } from '../../../redux/store.ts';
import { updateShoppingCart } from '../../../redux/reducers/app.ts';
import { ShowSkuSelectionPopup } from './SkuSelectionPopup.tsx';
import { Touchable } from 'react-native-toast-message/lib/src/components/Touchable';
import RenderPrice from '../merchantProduct/component/RenderPrice.tsx';
import RenderingDiscount from '../merchantProduct/component/RenderingDiscount.tsx';
import { navigate } from '../../../common/navigationService.ts';
import { ShowSkuPackageSelectionPopup } from './SkuPackageSelectionPopup.tsx';

interface IProductItemProps {
  item: IProductInformation;
}
const ProductItem: React.FC<IProductItemProps> = ({ item }) => {
  const shoppingCart = useSelector((state: RootState) => state.shoppingCart);
  const [shoppingCartProduct, setShoppingCartProduct] = useState<IProductInformation | undefined>(undefined);
  const dispatch = useDispatch<AppDispatch>();

  useEffect(() => {
    setShoppingCartProduct(shoppingCart.find((_item) => _item.goodsId === item.goodsId));
  }, [shoppingCart]);

  // 添加产品购物车
  const handleOperationProductToShoppingCart = (type: 'add' | 'remove', data: IProductInformation) => {
    dispatch(updateShoppingCart({ type, data }));
  };

  return (
    <React.Fragment>
      <Touchable style={[styles.list, { opacity: Tools.renderProductValidation(item) <= 2 ? 0.4 : 1 }]} onPress={() => navigate('productDetails', { product: item })}>
        <View style={styles.imgBox}>
          <FasterImageView style={{ flex: 1 }} source={{ url: item.mainImage, transitionDuration: 0.3, resizeMode: 'cover', cachePolicy: 'discWithCacheControl', showActivityIndicator: true, borderRadius: 8 }} />
          {item.oneIsVideo === 2 && (
            <View style={styles.mask}>
              <AntDesign name={'play'} size={33} />
            </View>
          )}
          {shoppingCart.find((_item) => _item.goodsId === item.goodsId) && (
            <View style={styles.badge}>
              <Text fontSize={10} color={'white'}>
                {shoppingCart.reduce((sum, _item) => {
                  if (_item.goodsId === item.goodsId) {
                    return sum + _item.nums;
                  }
                  return sum;
                }, 0)}
              </Text>
            </View>
          )}
        </View>
        <View style={styles.right}>
          <View style={styles.top}>
            <Text flex={1} numberOfLines={1} fontWeight={'bold'} fontSize={12}>
              {item.name}
            </Text>
            {item.visitFlag !== 0 && (
              <View>
                <Text fontSize={10} borderWidth={0.5} borderColor={CommonStyle.lightGray} borderRadius={4} paddingX={1}>
                  服务上门
                </Text>
              </View>
            )}
          </View>
          {item.introduce && (
            <View width={'100%'} paddingY={1}>
              <Text fontSize={10} numberOfLines={2} backgroundColor={'#ec820d'} color={CommonStyle.lightGray}>
                {item.introduce}
              </Text>
            </View>
          )}
          {item.remark && (
            <View width={'100%'} paddingY={1}>
              <Text fontSize={10} numberOfLines={2} backgroundColor={'#ec820d'} color={CommonStyle.lightGray}>
                {item.remark}
              </Text>
            </View>
          )}
          {RenderingDiscount(item, shoppingCart)}
          <View style={styles.price}>
            {Tools.renderProductValidation(item) > 2 && RenderPrice(item, shoppingCart)}
            <View>
              {Tools.renderProductValidation(item) <= 2 && (
                <View flex={1} width={'100%'} flexDirection={'row'} justifyContent={'space-between'}>
                  <View />
                  <Text paddingX={2} fontSize={13} textAlign={'right'} color={CommonStyle.deepGrey}>
                    {Tools.renderProductValidation(item) === 1 ? '非可售时间' : '已售罄'}
                  </Text>
                </View>
              )}
              {Tools.renderProductValidation(item) === 3 && (
                <TouchableOpacity
                  onPress={() => {
                    if (item.goodsType === 2) {
                      ShowSkuPackageSelectionPopup.show(item);
                    } else {
                      ShowSkuSelectionPopup.show(item);
                    }
                  }}
                >
                  <View backgroundColor={CommonStyle.mainColor} borderRadius={8}>
                    <Text paddingX={2} fontSize={13} color={'#fff'}>
                      选规格
                    </Text>
                  </View>
                </TouchableOpacity>
              )}
              {Tools.renderProductValidation(item) === 4 && (
                <View flexDirection={'row'}>
                  {shoppingCartProduct && (
                    <>
                      <TouchableOpacity onPress={() => handleOperationProductToShoppingCart('remove', item)}>
                        <Ionicons name={'remove-circle'} size={26} color={CommonStyle.mainColor} />
                      </TouchableOpacity>
                      <Text mx={2}>{shoppingCartProduct.nums}</Text>
                    </>
                  )}
                  <TouchableOpacity onPress={() => handleOperationProductToShoppingCart('add', item)}>
                    <Ionicons name={'add-circle'} size={26} color={CommonStyle.mainColor} />
                  </TouchableOpacity>
                </View>
              )}
            </View>
          </View>
        </View>
      </Touchable>
    </React.Fragment>
  );
};
const styles = StyleSheet.create({
  list: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8, paddingVertical: 10 },
  imgBox: { width: 80, height: 80, borderRadius: 8, position: 'relative' },
  mask: { position: 'absolute', width: 80, height: 80, top: 0, backgroundColor: 'rgba(0,0,0,0.1)', zIndex: 9, alignItems: 'center', justifyContent: 'center' },
  right: { flex: 1, paddingLeft: 12, minHeight: 80, justifyContent: 'space-between' },
  top: { flexDirection: 'row', justifyContent: 'space-between', width: '100%' },
  price: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', width: '100%' },
  badge: { position: 'absolute', width: 20, height: 20, backgroundColor: 'red', right: -5, top: -10, zIndex: 9, borderRadius: 10, justifyContent: 'center', alignItems: 'center' },
});

export default React.memo(ProductItem);
